/*
 * Copyright (c) 2005 -2008 Reliable Source, Inc. and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Mozilla Public License v.1.1,
 * BSD, and Eclipse Public License v1.0 which accompanies this
 * distribution and is available at:
 *
 * 		http://www.eclipse.org/legal/epl-v10.html
 * 		http://www.opensource.org/licenses/bsd-license.php
 * 		http://www.mozilla.org/MPL/MPL-1.1.html
 *
 * Contributors:
 *     IBM Corporation	     -  http://ibm.com
 *     	- initial API and implementation
 *
 *     patientos.org         - http://patientos.org
 *     	- domain and database persistence layer
 *
 *     Reliable Source, Inc. - http://reliablesource.org
 *     	- Symbiosys Application Framework,
 *     	- Symbiosys Application, Symbiosys Product
 *
 */
package org.reliablesource.symbiosys.platform.viewers;

import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ITableLabelProvider;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.Composite;
import org.reliablesource.client.ui.symbiosys.platform.SymbiosysPlatformActivator;
import org.reliablesource.client.ui.viewers.ElementTableViewer;
import org.reliablesource.model.core.ReliableNode;

import com.patientis.client.service.patient.PatientService;
import com.patientis.client.state.State;
import com.patientis.model.common.IBaseModel;
import com.patientis.model.patient.ViewPatientModel;
import com.patientis.model.reference.ContextReference;

public class PatientListViewer extends ElementTableViewer implements
	PropertyChangeListener {
    public static final int LASTNAME = 0;
    public static final int FIRSTNAME = 1;
    public static final int MRN = 2;
    public static final int DOB = 3;
    public static final int GENDER = 4;
    public static final int SSN = 5;
    public static final int PHONE = 6;
    public static final String[] COLUMNS = { "Last name", "First name", "MRN",
	    "Birthdate", "Gender", "SSN", "Phone" };

    List<ReliableNode> viewPatientModelList;

    public PatientListViewer() {
	super();
	viewPatientModelList = new ArrayList<ReliableNode>();
    }

    @Override
    public void createViewerControl(Composite _parent) {
	super.createViewerControl(_parent);

	contentViewer.setContentProvider(new ViewContentProvider());
	contentViewer.setLabelProvider(new ViewLabelProvider());
	addChild(contentViewer);

	setInput(fetchData());
    }

    protected Object fetchData() {
	List<ViewPatientModel> patients = null;

	try {
	    // PatientListController _patientListController =
	    // PatientListController
	    // .getInstance(ISApplicationMediator.getInstance(),
	    // ApplicationController.getInstance());

	    patients = PatientService.getPatientsByPatientList(State
		    .getUserRefId(), ContextReference.PATIENTLISTMYPATIENTS
		    .getRefId());
	} catch (Exception _e) {

	}

	Iterator<ViewPatientModel> _it = patients.iterator();

	while (_it.hasNext()) {
	    ViewPatientModel _vpm = _it.next();
	    _vpm.addPropertyChangeListener(this);
	    ReliableNode _node = new ReliableNode();
	    _node.setModel(_vpm);
	    viewPatientModelList.add(_node);
	}

	return viewPatientModelList;
    }

    @Override
    public String[] getColumns() {
	return COLUMNS;
    }

    @Override
    public void setInput(Object input) {
	contentViewer.setInput(input);
    }

    @Override
    public ISelection getSelection() {
	return contentViewer.getSelection();
    }

    /**
     * The content provider class is responsible for providing objects to the
     * view. It can wrap existing objects in adapters or simply return objects
     * as-is. These objects may be sensitive to the current input of the view,
     * or ignore it and always show the same content (like Task List, for
     * example).
     */
    class ViewContentProvider implements ITreeContentProvider {
	public void inputChanged(Viewer v, Object oldInput, Object newInput) {
	    if (v != null) {
		if (oldInput != null) {
		    if (newInput != null) {
			if (oldInput != newInput)
			    v.setInput(newInput);
		    }
		}
	    }
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.eclipse.jface.viewers.IStructuredContentProvider#getElements(
	 * java.lang.Object)
	 */
	public Object[] getElements(Object parent) {

	    if (parent instanceof Collection)
		return ((Collection) parent).toArray();
	    return new Object[0];
	}

	public Object[] getChildren(Object parentElement) {
	    IBaseModel _vpm = (IBaseModel) parentElement;

	    return _vpm.getChildren().toArray();
	}

	public Object getParent(Object element) {
	    return null;
	}

	public boolean hasChildren(Object element) {
	    return false;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.jface.viewers.IContentProvider#dispose()
	 */
	public void dispose() {
	    // TODO Auto-generated method stub

	}
    }

    class ViewLabelProvider extends LabelProvider implements
	    ITableLabelProvider {
	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.eclipse.jface.viewers.ITableLabelProvider#getColumnText(java.
	 * lang.Object, int)
	 */
	public String getColumnText(Object obj, int index) {
	    ViewPatientModel _vpm = (ViewPatientModel) ((ReliableNode) obj)
		    .getModel();

	    try {
		switch (index) {
		case LASTNAME:
		    return _vpm.getLastName();

		case FIRSTNAME:
		    return _vpm.getFirstName();

		case MRN:
		    return _vpm.getId().toString();

		case DOB:
		    return _vpm.getBirthDt().toString();

		case GENDER:
		    return _vpm.getGenderRef().getDisplay();

		case SSN:
		    return _vpm.getId().toString();

		case PHONE:
		    return _vpm.getPhones().get(0).getPhoneNumber();
		}
	    } catch (Exception _e) {
		return "";
	    }

	    return getText(obj);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.eclipse.jface.viewers.ITableLabelProvider#getColumnImage(java
	 * .lang.Object, int)
	 */
	public Image getColumnImage(Object obj, int index) {
	    return null;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.eclipse.jface.viewers.LabelProvider#getImage(java.lang.Object)
	 */
	public Image getImage(Object obj) {
	    // return PlatformUI.getWorkbench().getSharedImages().getImage(
	    // ISharedImages.IMG_OBJ_ELEMENT);
	    return null;
	}
    }

    /*
     * (non-Javadoc)
     * 
     * @seejava.beans.PropertyChangeListener#propertyChange(java.beans.
     * PropertyChangeEvent)
     */
    public void propertyChange(PropertyChangeEvent _evt) {
	String _propertyName = _evt.getPropertyName();

	Object _new_ = _evt.getNewValue();
	Object _old_ = _evt.getOldValue();

	System.err.println("Recieved Property change event for prop:  "
		+ _propertyName);
	System.err.println("From:" + _old_.toString());
	System.err.println("To:" + _new_.toString());
    }

    @Override
    public void dispose() {
	List<ReliableNode> _input = (List<ReliableNode>) getInput();

	for (int i = 0; i < _input.size(); i++) {
	    IBaseModel _model = ((IBaseModel) _input.get(i).getModel());
	    _model.removePropertyChangeListeners();
	}
	super.dispose();
    }
}
